/**
 * @editor: nguyen anh que
 * Danh bạ lấy từ server về
 */
package com.vnp.vchat.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.adapter.SearchAdapter;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.database.DBAdapter;
import com.vnp.vchat.database.DBFunction;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;
import com.vnp.vchat.util.Common;
import com.vnp.vchat.util.PreferenceHelper;
import com.vnp.vchat.util.Utils;
import com.vnp.vchat.version2.ChatNewActivity;

public class DanhbaScr extends DanhbaSrcInit {

	TextView title;
	ListView listContact;
	PreferenceHelper preferenceHelper;
	String hash;

	SearchAdapter adapter;

	ArrayList<ObjKhachhang> objKhachhangs = new ArrayList<ObjKhachhang>();

	private ArrayList<ObjKhachhang> text_sort = new ArrayList<ObjKhachhang>();
	private ArrayList<Integer> image_sort = new ArrayList<Integer>();
	public int textlength = 0;
	EditText editSearch;
	ImageView ic_search_db;
	private Dialog dialog;
	int page = 0;

	RelativeLayout llProgressBar;
	TextView txtNoContact;
	ProgressBar progressBar;

	private int preLast;
	boolean isLoading = false;
	Handler mHandler = new Handler();
	private InputMethodManager imm;
	Runnable r = new Runnable() {

		@Override
		public void run() {
			getDanhba(++page);
		}
	};

	DBFunction dbFunction;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		dbFunction = new DBFunction(DBAdapter.getObj(getActivity()));
		dbFunction.getContactSV();
		preferenceHelper = new PreferenceHelper(getActivity());
		hash = Utils.MD5(Common.KEY_HTTP + "|" + preferenceHelper.getUserId());
	}

	ViewGroup viewGroup;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (viewGroup == null) {
			viewGroup = (ViewGroup) inflater.inflate(R.layout.scr_danhba,
					container, false);
		} else {
			((ViewGroup) viewGroup.getParent()).removeView(viewGroup);
		}
		ic_search_db = (ImageView) viewGroup.findViewById(R.id.ic_search_db);
		editSearch = (EditText) viewGroup.findViewById(R.id.edt_search_db);
		editSearch.setTypeface(Utils.getTypefaceRegular(getActivity()), Typeface.NORMAL);
		title = (TextView) viewGroup.findViewById(R.id.title);
		
		listContact = (ListView) viewGroup.findViewById(R.id.list_contact);
		txtNoContact = (TextView) viewGroup.findViewById(R.id.txt_no_contact);
		progressBar = (ProgressBar) viewGroup.findViewById(R.id.progressBar1);

		llProgressBar = (RelativeLayout) viewGroup
				.findViewById(R.id.ll_progress_bar);

		objKhachhangs.addAll(dbFunction.getContactSV());
		editSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

				textlength = editSearch.getText().toString().length();
				text_sort.clear();
				image_sort.clear();
				String searchName = editSearch.getText().toString();
				if (objKhachhangs != null) {
					for (int i = 0; i < objKhachhangs.size(); i++) {
						if (textlength <= objKhachhangs.get(i).toString()
								.length()) {
							String contactName = objKhachhangs.get(i).getName();
							if (contactName.toLowerCase().contains(searchName.toLowerCase())) {
								text_sort.add(objKhachhangs.get(i));
							}
						}
					}

					if (editSearch.isFocused() == true) {
						adapter = new SearchAdapter(getActivity(), text_sort);
						listContact.setAdapter(adapter);
					} else {
						new getContactTask().execute();
						text_sort.clear();
						image_sort.clear();
					}

				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		init();
		setFont();

		getDanhba(page);

		listContact.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

				int lastItem = firstVisibleItem + visibleItemCount;
				if (lastItem == totalItemCount) {
//					if (preLast != lastItem) {
//						int last_pos = listContact.getLastVisiblePosition();
//						if (last_pos >= objKhachhangs.size() - 1) {
//							llProgressBar.setVisibility(View.VISIBLE);
//							mHandler.removeCallbacks(r);
//							mHandler.postDelayed(r, 500);
//						}
//						preLast = lastItem;
//					}

				}
			}
		});

		listContact.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				
				ObjKhachhang ojSend = (ObjKhachhang) arg0.getAdapter().getItem(position);
				
				MainPanelActivity.onGoto = true;
				Intent c = new Intent(getActivity(), ChatNewActivity.class);
				c.putExtra("khachhang", ojSend);
				startActivity(c);
				getActivity().overridePendingTransition(R.anim.trans_left_in,
						R.anim.over_main_left);
			}

		});
		return viewGroup;
	}

	void init() {
		title.setText("Danh bạ");
	}

	void setFont() {
		title.setTypeface(Utils.getTypefaceRegular(getActivity()), Typeface.BOLD);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		new getContactTask().execute();

		if (imm != null) {
			imm.hideSoftInputFromWindow(editSearch.getWindowToken(), 0);
		}
		editSearch.setText("");

	}

	private class getContactTask extends
			AsyncTask<Void, Void, ArrayList<ObjKhachhang>> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected ArrayList<ObjKhachhang> doInBackground(Void... params) {
			// TODO Auto-generated method stub
			objKhachhangs = dbFunction.getContactSV();
			return objKhachhangs;
		}

		@Override
		protected void onPostExecute(ArrayList<ObjKhachhang> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			adapter = new SearchAdapter(getActivity(), objKhachhangs);
			listContact.setAdapter(adapter);
			text_sort.clear();
			image_sort.clear();

		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		editSearch.clearComposingText();
		editSearch.clearFocus();

	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (editSearch.isFocused()) {
			InputMethodManager imm = (InputMethodManager) getActivity()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(editSearch.getWindowToken(), 0);
		}
	}

	void getDanhba(int page) {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						progressBar.setVisibility(View.GONE);
						llProgressBar.setVisibility(View.GONE);
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							int status = re.getInt("status");
							progressBar.setVisibility(View.GONE);
							llProgressBar.setVisibility(View.GONE);
							if (status == 1) {
								JSONArray ja = re.getJSONArray("data");

								Log.i("DATA", "DANH BA: " + ja.toString());

								if (ja.length() > 0) {
									for (int i = 0; i < ja.length(); i++) {
										JSONObject jo = ja.getJSONObject(i);

										int id = jo.getInt("id");
										String name = jo.getString("name");
										String avatar = jo.getString("avatar");
										String contact = jo
												.getString("contact");
										// String from = jo.getString("from");

										ObjKhachhang objKhachhang = new ObjKhachhang();
										objKhachhang.setId(String.valueOf(id));
										objKhachhang.setName(name);
										objKhachhang.setUrlAvatar(avatar);
										objKhachhang.setLoginName(contact);
										objKhachhang.setUrlDangxem("");

										objKhachhangs.add(objKhachhang);

										dbFunction
												.updateContactSV(objKhachhang);
										
										
										
									}
									
									mHandler.removeCallbacks(r);
									mHandler.postDelayed(r, 500);
									
									
								} else {
									txtNoContact.setVisibility(View.VISIBLE);
								}
								objKhachhangs.clear();
								objKhachhangs.addAll(dbFunction.getContactSV());

							} else {
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

				});
		httpClientHelper.getContact(preferenceHelper.getAdminId(),
				preferenceHelper.getHashSetting(), page);
	}

}
